//
//  ListViewController.m
//  shareTest
//
//  Created by liliang on 13-5-17.
//  Copyright (c) 2013年 李 良. All rights reserved.
//

#import "ShareViewController.h"
//#import "Reachability.h"
#import "toolbox.h"

@interface ShareViewController ()

@end

@implementation ShareViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.shareArray = [NSMutableArray array];

    //JSON解析
//    NSError *error = nil;
//    NSString *str = [[NSBundle mainBundle] pathForResource:@"share.html" ofType:nil];
//    NSURL *url = [NSURL fileURLWithPath:str];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    self.shareDictionary = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

    NSData *data=[self loadResource:@"share.json"];
    self.shareDictionary=data.jsonObject;

//    self.shareDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"share.plist" ofType:nil]];

    if (self.shareDictionary[@"weibo"]) {
        [self.shareArray addObject:self.shareDictionary[@"weibo"]];
         //向微博注册
        [WeiboSDK enableDebugMode:YES];
        [WeiboSDK registerApp:self.shareDictionary[@"weibo"][@"appkey"]];
    }
    if (self.shareDictionary[@"weixin"]) {
        [self.shareArray addObject:self.shareDictionary[@"weixin"]];
        //向微信注册
        [WXApi registerApp:self.shareDictionary[@"weixin"][@"appid"]];
    }
    if (self.shareDictionary[@"email"]) {
        [self.shareArray addObject:self.shareDictionary[@"email"]];
    }

//    [self judgeTheNetwork];
}

-(NSData *)loadResource:(NSString *)filename{
    NSData *data=nil;
    if (filename.docPath.isFile) {
        data=[NSData dataWithContentsOfFile:filename.docPath];
    }
    if (filename.mediaPath.isFile) {
        data=[NSData dataWithContentsOfFile:filename.mediaPath];
    }
    return data;
}


//-(BOOL)judgeTheNetwork
//{
//    BOOL isExistenceNetwork = YES;
//    NSString *str = [NSString string];
//    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
//    switch ([r currentReachabilityStatus]) {
//        case NotReachable:
//            isExistenceNetwork=NO;
//            str = @"没有网络";
//            break;
//        case ReachableViaWWAN:
//            isExistenceNetwork=YES;
//            str = @"正在使用3G网络";
//            break;
//        case ReachableViaWiFi:
//            isExistenceNetwork=YES;
//            str = @"正在使用wifi网络";
//            break;
//    }
//    UIAlertView *myalert = [[UIAlertView alloc]
//                            initWithTitle:nil
//                            message:str
//                            delegate:self
//                            cancelButtonTitle:@"确定"
//                            otherButtonTitles:nil];
//        
//    [myalert show];  
//
//
//    return isExistenceNetwork;
//}

#pragma mark UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (alertView.tag == 1000) {
        if (buttonIndex == 1) {
            NSString *string = @"http://itunes.apple.com/cn/app/id350962117?mt=8";
            [[UIApplication sharedApplication] openURL: [NSURL URLWithString:string]];
        }
    }
    if (alertView.tag == 1001) {
        if (buttonIndex == 1) {
            NSString *string = [WXApi getWXAppInstallUrl];
            [[UIApplication sharedApplication] openURL: [NSURL URLWithString:string]];
        }
    }
    if (alertView.tag == 1002) {
        if (buttonIndex == 0) {

        }
        if (buttonIndex == 1) {
            NSString *recipients = @"mailto:first@example.com&subject=my email!";
            NSString *body = @"&body=email body!";
            NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
            email = [email stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
        }
    }
}


-(void)setEmailWithTitle:(NSString *)title content:(NSString *)content forRecipient:(NSArray *)recipients
{
    MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
    controller.mailComposeDelegate = self;
    [controller setSubject:title];
    [controller setToRecipients:recipients];
    [controller setMessageBody:content isHTML:YES];
    [self presentViewController:controller animated:YES completion:nil];

}
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error{
    if (result == MFMailComposeResultSent) {
        [self alertWithTitle:nil message:@"邮件发送成功"];
    }
    else if (result == MFMailComposeResultCancelled)
    {
        [self alertWithTitle:nil message:@"邮件发送取消"];
    }
    else if (result == MFMailComposeResultSaved)
    {
        [self alertWithTitle:nil message:@"邮件保存成功"];
    }
    else if (result == MFMailComposeResultFailed)
    {
        [self alertWithTitle:nil message:@"邮件发送失败"];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) alertWithTitle: (NSString *)title message: (NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
  
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscape;
}

-(ShareViewController *)initWithTitle:(NSString *)title
                             content:(NSString *)content
                                 url:(NSURL *)url
{
    self = [super init];
    if (self) {
        self.titleStr = title;
        self.contentStr = content;
        self.url = url;
    }
    return self;
}

-(void)show
{
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self];
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
    [self.delegate presentViewController:nav animated:YES completion:nil];

    //[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"IndexSep.png"] forBarMetrics:UIBarMetricsDefault];
    UITableView *listTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    listTableView.delegate = self;
    listTableView.dataSource = self;
    [self.view addSubview:listTableView];

    //UIButton *leftBtn = [[UIButton alloc] init];
    //[leftBtn setBackgroundImage:[UIImage imageNamed:@"NavigationButtonBG.png"] forState:UIControlStateNormal];
    //[leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    //leftBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    //leftBtn.frame = CGRectMake(0.0, 0.0, 53.0, 30.0);
    //[leftBtn addTarget:self action:@selector(cancelButtonClickHandler:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonClickHandler:)];//[[UIBarButtonItem alloc] initWithCustomView:leftBtn];

    self.title =LOC_STR(@"分享");
}

-(void)cancelButtonClickHandler:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark UITableViewdDeletage
#pragma mark UITableViewDataSource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.shareArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"list"];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"list"];
        cell.clipsToBounds=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    cell.textLabel.text = self.shareArray[indexPath.row][@"type"];
    cell.imageView.image = [UIImage imageNamed:self.shareArray[indexPath.row][@"image"]];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"点击分享到%@",self.shareArray[indexPath.row][@"type"]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.shareArray[indexPath.row][@"type"] isEqualToString:@"新浪微博" ]) {
        if ([WeiboSDK isWeiboAppInstalled]) {
            WBMessageObject *message = [WBMessageObject message];
            //要发送的文本
            message.text = [NSString concatStrings:self.titleStr,@" ",self.url.absoluteString, nil];//[self.titleStr stringByAppendingString:self.contentStr];
            WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message];
            request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                                 @"Other_Info_1": [NSNumber numberWithInt:123],
                                 @"Other_Info_2": @[@"obj1", @"obj2"],
                                 @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};


            [WeiboSDK sendRequest:request];

//            WBAuthorizeRequest *request = [WBAuthorizeRequest request];
//            NSString *str = self.shareDictionary[@"weibo"][@"redirectUril"];
//            request.redirectURI = str;
//            request.scope = @"email,direct_messages_write";
//            request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
//                                 @"Other_Info_1": [NSNumber numberWithInt:123],
//                                 @"Other_Info_2": @[@"obj1", @"obj2"],
//                                 @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
//            [WeiboSDK sendRequest:request];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                            message:@"尚未安装微博客户端，是否现在去安装"
                                                           delegate:self
                                                  cancelButtonTitle:@"以后再说"
                                                  otherButtonTitles:@"现在安装", nil];
            alert.tag = 1000;
            [alert show];
        }

    }
    if ([self.shareArray[indexPath.row][@"type"] isEqualToString:@"邮件" ])
    {
        Class mailClass = NSClassFromString(@"MFMailComposeViewController");
        if (mailClass != nil) {
            if ([mailClass canSendMail]) {
                NSString *ctx=[NSString concatStrings:@"<p>",self.contentStr,@"</p>",@"<a href='",self.url.absoluteString,@"'>",self.url.absoluteString,@"</a>", nil];
                [self setEmailWithTitle:self.titleStr content:ctx forRecipient:nil];
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有设置邮箱，是否设置?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alert.tag = 1002;
                [alert show];
            }

        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有设置邮箱，是否设置?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 1002;
            [alert show];
        }

    }

      if ([self.shareArray[indexPath.row][@"type"] isEqualToString:@"微信" ]){
        if ([WXApi isWXAppInstalled]) {
            SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
            req.bText = YES;
            //要发送的文本
            req.text = [NSString concatStrings:self.titleStr,@" ",self.url.absoluteString, nil];//self.titleStr;
            req.scene = WXSceneTimeline;
            [WXApi sendReq:req];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"尚未安装微信客户端，是否现在去安装"
                                                           delegate:self
                                                  cancelButtonTitle:@"以后再说"
                                                  otherButtonTitles:@"现在安装", nil];
            alert.tag = 1001;
            [alert show];
        }
    }
}

@end

void socialNetwork(id delegate,NSString *serialized){
    NSDictionary *dictionary=serialized.urldecode.toDictionary;
    NSURL *url=[NSURL URLWithString:dictionary[@"url"]];
    ShareViewController *vc=[[ShareViewController alloc] initWithTitle:dictionary[@"title"] content:dictionary[@"content"] url:url];
    vc.delegate=delegate;
    [vc show];
}


